#!/bin/bash

function usage() {
    echo "Usage:$( basename $0 ) [-f <bz2 file name> | -x ] <src>"
    echo "    tar -cjf <bz2 file name> <src>并提示进度"
    echo "    -f <bz2 file name>: 输出文件名"
    echo "    -x: 解压-f指定的tar.bz2文件"
    exit 1
}

untar=false
shiftCnt=0
while getopts "xf:" arg
do
    case "${arg}" in
        x)
            untar=true
            shiftCnt=$(( ${shiftCnt} + 1 ))
            ;;
        f)
            file_name=${OPTARG}
            shiftCnt=$(( ${shiftCnt} + 2 ))
            ;;
        *)
            usage
            ;;
    esac
done

shift ${shiftCnt}

src=$1

if [ -z "${file_name}" ]
then
    echo "ERROR: -f <bz2 file name>是必须的"
    usage
fi

if ! ${untar}
then
    if [ -z "${src}" -o ! -e "${src}" ]
    then
        echo "ERROR: 源文件未指定或不存在"
        usage
    fi
else
    if [ ! -e "${file_name}" ]
    then
        echo "ERROR: ${file_name}不存在"
        exit 1
    fi
fi

if ${untar}
then
    size=$(du -sb ${file_name} | awk '{print $1}')
    bzip2 -d ${file_name} -c | pv -s ${size} | tar -x
else
    size=$(du -sb ${src} | awk '{print $1}')
    tar -cf - ${src} | pv -s ${size} | bzip2 > ${file_name}
fi
